package org.example;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;


/**
 * dataset
 * 批处理实现wordcount
 */
public class TestWordCount {

    public static void main(String[] args) throws Exception {
        //创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        DataSource<String> dataSource = env.readTextFile("hello.txt");

        //主要离线数据集
        FlatMapOperator<String, Tuple2<String, Integer>> operator = dataSource.flatMap((String s, Collector<Tuple2<String, Integer>> collector) -> {
            String[] words = s.split(" ");
            for (String word : words) {
                collector.collect(Tuple2.of(word, 1));
            }

        }).returns(Types.TUPLE(Types.STRING, Types.INT));


        AggregateOperator<Tuple2<String, Integer>> sum = operator.groupBy(0).sum(1);
        sum.print();



    }
}


